package com.gjy.batch.job;

import com.gjy.batch.module.StudentInfo;
import com.gjy.batch.module.file.StudentFile;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.database.JpaItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManagerFactory;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-03 08:58:10
 */
@Component
public class StudentJob {

    @Bean
    public FlatFileItemReader<StudentFile> studentInfoReader(@Value("${input.file}") Resource resource) { // 文件路径如 classpath:sample.csv

        BeanWrapperFieldSetMapper<StudentFile> mapper = new BeanWrapperFieldSetMapper<>();
        mapper.setTargetType(StudentFile.class);

        return new FlatFileItemReaderBuilder<StudentFile>()
                .name("studentReader")
                .resource(resource)
                .linesToSkip(1) // 跳过 CSV 标题行
                .delimited()
                .names("id", "name", "age", "sex", "address", "phone") // 列名与 CSV 对齐
                .fieldSetMapper(mapper)
                .build();
    }

    @Bean
    public JpaItemWriter<StudentInfo> studentInfoWriter(EntityManagerFactory entityManagerFactory) {
        JpaItemWriter<StudentInfo> writer = new JpaItemWriter<>();
        writer.setEntityManagerFactory(entityManagerFactory);
        return writer;
    }

    @Bean
    public ItemProcessor<StudentFile, StudentInfo> studentInfoProfessor() {
        return item -> {
            StudentInfo si = new StudentInfo();
            BeanUtils.copyProperties(item, si);
            if (si.getAge() < 18) {
                si.setAge(18);
            }
            return si;
        };
    }
}
